package kook.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import kook.messageheadler.ChannelMessageHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import kook.util.CryptUtils;

@Controller
@ResponseBody
@RequestMapping
public class EventController {
    @Autowired
    private ObjectMapper objectMapper;
    @Value("${protocol.encrypt-key}")
    private String encryptKey;   // 消息解密
    @Value("${protocol.verify-token}")
    private String verifyToken;    // 握手认证token
    @Autowired
    private ChannelMessageHandler channelMessageHandler;

    @PostMapping("/event")
    public Object event(@RequestBody JsonNode jsonNode) throws JsonProcessingException {
        // 消息解密
        jsonNode = objectMapper.readTree(CryptUtils.decrypt(jsonNode.get("encrypt").asText(), encryptKey));
        // body 固定格式
        // 信令类型
        int s = jsonNode.get("s").asInt();
        // 数据
        JsonNode dataNode = jsonNode.get("d");
        System.out.println(jsonNode);

        if (s == 0) {
            String channelType = dataNode.get("channel_type").asText();
            // 握手协议
            if (channelType.equals("WEBHOOK_CHALLENGE")) {
                if (dataNode.get("verify_token").asText().equals(verifyToken)) {
                    return objectMapper.createObjectNode().put("challenge", dataNode.get("challenge").asText());
                } else {
                    return null;
                }
            } else if (channelType.equals("GROUP")) {
                channelMessageHandler.handler(dataNode);
            } else if (channelType.equals("PERSON")) {
                return null;
            }
        }
        return null;
    }
}
